//
//  H5ViewController.m
//  ExampleApp-iOS
//
//  Created by Marcus Westin on 1/13/14.
//  Copyright (c) 2014 Marcus Westin. All rights reserved.
//

#import "H5ViewController.h"
#import "WebViewJavascriptBridge.h"
#import "UpdateHeadPhotoViewController.h"
#import "UserRequest.h"
#import "AddCarViewController.h"
#import "LoginViewController.h"
#import "BaseNavigationController.h"
#import "AppDelegate.h"
#import "UserModel.h"

#import "Cycling-Swift.h"

@interface H5ViewController ()

@property WebViewJavascriptBridge* bridge;

@end

@implementation H5ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    if (_bridge) { return; }
    WKWebView* webView = [[NSClassFromString(@"WKWebView") alloc] initWithFrame:self.view.bounds];
    [webView setOpaque:NO];
    webView.navigationDelegate = self;
    webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [self loadExamplePage:webView];

    [self.view addSubview:webView];
    
    [WebViewJavascriptBridge enableLogging];
    _bridge = [WebViewJavascriptBridge bridgeForWebView:webView];
    [_bridge setWebViewDelegate:self];

    // js调用oc传token，语言
    [_bridge registerHandler:@"loadUserInfo" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        NSString *token = [USERDEFAULTS valueForKey:@"Token"];
        NSString *language = [[CycLanguage sharedInstance] currentLanguage];
        responseCallback(@{@"token":token,@"lang":language});
    }];
    
    // js调用oc传状态栏高度
    [_bridge registerHandler:@"getTopHeight" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        NSString *height = [NSString stringWithFormat:@"%f",SafeAreaTopHeight];
        responseCallback(@{@"height":height});
    }];
    
    [_bridge registerHandler:@"chooseCars" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        NSLog(@"========= chooseCars");
        //ios参数 {id:'12'}
    }];
    
    [_bridge registerHandler:@"addCarsclick" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        NSLog(@"========= addCarsclick");
        [self addCar];
    }];
    
    [_bridge registerHandler:@"clearHistory" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        NSLog(@"========= clearHistory");

    }];
    [_bridge registerHandler:@"onBackPress" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"========= onBackPress");

        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [_bridge registerHandler:@"startEditHead" handler:^(id data, WVJBResponseCallback responseCallback) {
        UpdateHeadPhotoViewController *vc = [[UpdateHeadPhotoViewController alloc] init];
        vc.model = self.model;
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    // 获取h5当前设置语言
    [_bridge registerHandler:@"getLangues" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"========= getLangues%@",data);
        NSString *language = data[@"id"];
        if([language isEqualToString:@"zh"]){
            language = @"zh-Hans";
        }
        [[CycLanguage sharedInstance] setLanguage:language];
        [[NSNotificationCenter defaultCenter] postNotificationName:CycLanguageNotification object:nil];
    }];

    // 打开苹果健康 -- 链接服务
    [_bridge registerHandler:@"getHealthServe" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"========= getHealthServe");

        [self openAppleHealthLink];
    }];
    //  连接设备 -- 健康见解
    [_bridge registerHandler:@"getManagementLink" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"========= getManagementLink");

        [self addCar];
    }];
    
    // 退出登陆 -- 设置
    [_bridge registerHandler:@"loginOut" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"========= loginOut");
        [UserRequest logoutResult:^(BOOL ret) {
            UserModel *user = [UserModel currentUserInfo];
            [[NSUserDefaults standardUserDefaults] setValue:nil forKey:@"Token"];
            [user updateUserInfo];
            [UserModel setLoginSatus:NO];
            appDelegate.window.rootViewController = [[BaseNavigationController alloc] initWithRootViewController:[[LoginViewController alloc] init]];
            [appDelegate.window makeKeyAndVisible];
        }];
    }];
    
    // h5修改信息
    [_bridge registerHandler:@"userInfoEdit" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"========= userInfoEdit %@ == %@",responseCallback,data);
    }];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

// 添加车辆
- (void)addCar {
    AddCarViewController  *vc = [AddCarViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

// 打开苹果健康
- (void)openAppleHealthLink {
    [self requestHealthAppAuthorizationOnComplete:^(BOOL granted, BOOL shouldOpenHealthApp) {
        if(shouldOpenHealthApp) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"x-apple-health://app/"]];
        }
    }];
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"webViewDidStartLoad");
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"webViewDidFinishLoad");
}

- (void)loadExamplePage:(WKWebView*)webView {
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

}
@end
